# -*- coding: utf-8 -*-
"""
Created on Fri Nov 01 16:52:16 2013

@author: jkwong
"""

# PBAR_CargoDarkCurrent.py


import glob, os
import numpy as np
import matplotlib.pyplot as plt
import PBAR_Cargo
from datetime import datetime
import time

baseDir = r'C:\Users\jkwong\Documents\Work\PBAR\data3\RawCargo'
#baseDir = r'M:\common\PROJECTS\PBAR(ISNAR)\PBAR Data\Backup\Backup mirror\scans\Raw'


fullFilenameList = glob.glob(os.path.join(baseDir, '*.raw.cargoimage'))
filenameList = []
timeStamp = []
timeEpoch = []
for f in fullFilenameList:
    a, b = os.path.split(f)
    filenameList.append(b)
    timeStamp.append(datetime.strptime(b[10:27], '%Y-%m-%d %H%M%S'))
    timeEpoch.append(time.mktime(datetime.strptime(b[10:27], '%Y-%m-%d %H%M%S').timetuple()))

timeEpoch = np.array(timeEpoch)
# filename PBARArray-2013-10-24 105250 0000
# get the time stampf of the files

noiseTimeBounds = [65, 125]

noiseMatrix = np.zeros((len(fullFilenameList), 548))
singleDetectorSignal = []

for (filenameIndex, filename) in enumerate(fullFilenameList):
    print(filenameIndex)
    dat = PBAR_Cargo.ReadCargoImage(filename)
    temp = dat[0][noiseTimeBounds[0]:noiseTimeBounds[1],:300].mean()
    noiseMatrix[filenameIndex, :] = dat[0][noiseTimeBounds[0]:noiseTimeBounds[1],:].mean(0)
    singleDetectorSignal.append(dat[0][:,76])

timeArray = (timeEpoch - timeEpoch[0])/3600.

# Check the raw signal
plt.figure()
cut = (noiseMatrix.mean(1) > 400) & (noiseMatrix.mean(1) < 700)

for (index, s) in enumerate(singleDetectorSignal):
    if cut[index]:
        plt.plot(s, label = '%3.3f' %timeArray[index])

plt.axis((65, 120, 0, 1000))
plt.legend()

# plot of noise in a couple detectors vs time
plt.figure()
plt.grid()

cut = noiseMatrix.mean(1) < 1000
timeArray = (timeEpoch - timeEpoch[0])/3600.

for i in xrange(70, 75):
    plt.plot(timeArray[cut], noiseMatrix[cut, i], label = '%s' %i)
plt.xlabel('Time (hours)')
plt.ylabel('Noise')
plt.legend()


# plot of noise in a couple detectors vs time
plt.figure()
plt.grid()

goodList = np.where(noiseMatrix.mean(1) < 1000)[0]


for i in goodList:
    plt.plot(np.arange(1, 549), noiseMatrix[i, :], label = '%s' %i)
plt.xlabel('Detector Number')
plt.ylabel('Noise')
    
#